package com.eusoft.book_manage.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.eusoft.book_manage.entity.User;
import com.eusoft.book_manage.service.UserService;

import com.eusoft.book_manage.util.JWTUtils;
import com.eusoft.book_manage.util.Result;
import com.eusoft.book_manage.util.ResultUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录模块
 * @author eusoft
 * @date 2021/10/20 9:30
 */
@RestController
public class LoginController {
    LineCaptcha lineCaptcha;

    @Resource
    private UserService userService;

    @GetMapping("/loginManage/getImageCode")
    public Result<Object> getImageCode(HttpServletRequest request){
        Map<String,String> data = new HashMap<>();
        RandomGenerator generator = new RandomGenerator("0123456789",4);
        lineCaptcha = CaptchaUtil.createLineCaptcha(80,24);

        request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode());
        lineCaptcha.setGenerator(generator);
        lineCaptcha.createCode();
        data.put("imageCodeKey",lineCaptcha.getCode());
        data.put("imageCodeBase64",lineCaptcha.getImageBase64Data());
        return ResultUtil.success(data);
    };

    @PostMapping("/loginManage/userLogin")
    public Result<Object> login(User user,String imageCodeKey){
        System.out.println(user);
        if(lineCaptcha.verify(imageCodeKey)){
            try {
                User userDB = userService.login(user);
                Map<String,String> data = new HashMap<>();
                data.put("token", JWTUtils.getToken(userDB.getAid()));
                data.put("name",userDB.getName());
                return ResultUtil.success(data);
            } catch (Exception e) {
                System.out.println(e.getMessage());
                return ResultUtil.error(-1,e.getMessage(),null);
            }
        }
        else{
            return ResultUtil.error(201,"验证码错误",null);
        }



    }






}
